package org.thirdHero.admin.web;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.thirdHero.admin.annotation.LoginAdmin;
import org.thirdHero.core.token.UserToken;
import org.thirdHero.core.token.UserTokenManager;
import org.thirdHero.core.util.bcrypt.BCryptPasswordEncoder;
import org.thirdHero.db.domain.SysUser;
import org.thirdHero.core.util.JacksonUtil;
import org.thirdHero.core.util.ResponseUtil;
import org.thirdHero.db.service.SysUserService;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/admin/login")
public class AuthController {
    private final Log logger = LogFactory.getLog(AuthController.class);

    @Resource
    private SysUserService sysUserService;
    @Resource
    private UserTokenManager userTokenManager;
    /*
     *  { username : value, password : value }
     */
    @PostMapping("/login")
    public Object login(@RequestBody String body){
        String username = JacksonUtil.parseString(body, "username");
        String password = JacksonUtil.parseString(body, "password");

        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            return ResponseUtil.badArgument();
        }

        List<SysUser> sysUser = sysUserService.findSysUser(username);
        Assert.state(sysUser.size() < 2, "同一个用户名存在两个账户");
        if(sysUser.size() == 0){
            return ResponseUtil.failLogin();
        }
        SysUser admin = sysUser.get(0);

        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        if(!encoder.matches(password + admin.getSalt(), admin.getPassword())){
            return ResponseUtil.fail(403, "账号密码不对");
        }

        String adminId = admin.getId();
        // token
        UserToken adminToken = userTokenManager.generateToken(adminId,admin);

        return ResponseUtil.ok(adminToken.getToken());
    }

    /*
     *
     */
    @PostMapping("/logout")
    public Object login(@LoginAdmin SysUser sysUser ){
        return ResponseUtil.ok();
    }
}
